package com.qs.education.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.ws.soap.AddressingFeature.Responses;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mysql.fabric.Response;
import com.qs.education.bean.api.PageBean;
import com.qs.education.bean.api.ResponseBean;
import com.qs.education.bean.api.ResponseListBean;
import com.qs.education.bean.beans.EducationTeacherResponse;
import com.qs.education.bean.entity.EducationGroup;
import com.qs.education.bean.entity.EducationSchool;
import com.qs.education.bean.entity.EducationSubject;
import com.qs.education.bean.entity.EducationTeacher;
import com.qs.education.bean.enums.ResponseStatus;
import com.qs.education.bean.service.BaseService;
import com.qs.education.bean.utils.BeanCopyNotNull;
import com.qs.education.bean.utils.GetNullProperties;
import com.qs.education.bean.utils.PasswordUtils;
import com.qs.education.bean.utils.TokenUtil;
import com.qs.education.service.IGroupAPIService;
import com.qs.education.service.ITeacherAPIService;

/**
 * @class TeacherAPIServiceImpl
 * @author Leon
 * @description
 * @date Nov 1, 2018
 */
@Service
public class TeacherAPIServiceImpl extends BaseService implements ITeacherAPIService {

	@Override
	public EducationTeacherResponse findTeacherByMobile(String mobile) {

		EducationTeacherResponse response = new EducationTeacherResponse();
		EducationTeacher teacher = null;

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", mobile);
		teacher = iEducationTeacherDao.findEducationTeacherByMobile(params);
		if (teacher == null) {
			response.setStatus("error");
			response.setMessage("该账号不存在");
		} else {
			response.setStatus("success");
			response.setMessage("该账号已存在");
		}
		return response;
	}

	@Transactional
	@Override
	public EducationTeacherResponse login(String mobile, String password) {

		EducationTeacherResponse response = new EducationTeacherResponse();
		EducationTeacher teacher = null;
		password = PasswordUtils.encodPassword(password);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", mobile);
		teacher = iEducationTeacherDao.findEducationTeacherByMobile(params);

		if (teacher == null) {
			response.setStatus("error");
			response.setMessage("该账号不存在");
		} else if (teacher.getPassword().equals(password)) {

			response.setStatus("success");
			response.setMessage("登录成功");
			String token = TokenUtil.createToken(teacher.getId().toString(), teacher.getName(), teacher.getPassword(),
					null);
			EducationTeacher paramsEducationTeacher = new EducationTeacher();
			BeanUtils.copyProperties(teacher, paramsEducationTeacher);
			paramsEducationTeacher.setTeacherToken(token);
			boolean status = iEducationTeacherDao.update(paramsEducationTeacher);

			if (status == false) {
				response.setStatus("error");
				response.setMessage("token存储失败");
			} else if (status == true) {
				teacher.setTeacherToken(token);
				BeanUtils.copyProperties(teacher, response);
			}
		} else {
			response.setStatus("error");
			response.setMessage("密码不正确，请重新尝试");
		}
		return response;
	}

	@Transactional
	@Override
	public EducationTeacherResponse quit(String mobile) {
		System.out.println("api service impl mobile:" + mobile);
		EducationTeacherResponse response = new EducationTeacherResponse();
		EducationTeacher teacher = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", mobile);
		teacher = iEducationTeacherDao.findEducationTeacherByMobile(params);
		System.out.println(teacher.getTeacherToken());
		teacher.setTeacherToken("");
		boolean status = iEducationTeacherDao.update(teacher);
		if (status == false) {
			response.setStatus("error");
			response.setMessage("退出失败");
		} else if (status == true) {
			response.setStatus("successs");
			response.setMessage("退出成功");
		}
		return response;
	}

	@Transactional
	@Override
	public EducationTeacherResponse forgetPassword(String mobile, String password) {
		EducationTeacherResponse response = new EducationTeacherResponse();
		password = PasswordUtils.encodPassword(password);

		EducationTeacher teacher = new EducationTeacher();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", mobile);
		teacher = iEducationTeacherDao.findEducationTeacherByMobile(params);
		teacher.setPassword(password);
		boolean status = iEducationTeacherDao.update(teacher);
		if (status == false) {
			response.setStatus("error");
			response.setMessage("密码修改失败，请重新尝试");
		} else {
			response.setStatus("success");
			response.setMessage("密码修改成功。");
		}
		return response;
	}

	@Transactional
	@Override
	public EducationTeacherResponse saveTeacherMobileAndPassword(String mobile, String password) {
		EducationTeacherResponse response = new EducationTeacherResponse();
		password = PasswordUtils.encodPassword(password);

		EducationTeacher teacher = new EducationTeacher();
		teacher.setMobile(mobile);
		teacher.setPassword(password);
		System.out.println(teacher.toString());
		boolean status = iEducationTeacherDao.save(teacher);
		if (status == false) {
			response.setStatus("error");
			response.setMessage("保存信息失败");
		} else {
			response.setStatus("success");
			response.setMessage("保存信息成功");
		}
		return response;
	}

	@Transactional
	@Override
	public EducationTeacherResponse perfectTeacherInfo(EducationTeacher teacher, Integer schoolId, Integer subjectId) {
		EducationTeacherResponse response = new EducationTeacherResponse();
		EducationTeacher Teacher = new EducationTeacher();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", teacher.getMobile());
		Teacher = iEducationTeacherDao.findEducationTeacherByMobile(params);
		teacher.setId(Teacher.getId());
		teacher.setPassword(Teacher.getPassword());

		System.out.println("schoolId" + schoolId);

		EducationSchool school = iEducationSchoolDao.get(EducationSchool.class, Long.parseLong(schoolId + ""));
		EducationSubject subject = iEducationSubjectDao.get(EducationSubject.class, subjectId);

		teacher.setSchool(school);
		teacher.setSubject(subject);
		boolean status = iEducationTeacherDao.update(teacher);
		if (status == false) {
			response.setStatus("error");
			response.setMessage("保存信息失败");
		} else {
			teacher = iEducationTeacherDao.findEducationTeacherByMobile(params);
			BeanUtils.copyProperties(teacher, response);
			response.setStatus("success");
			response.setMessage("保存信息成功");
		}
		return response;
	}

	@Override
	public ResponseListBean<EducationTeacher> findTeacherByMobileOrName(String content) {
		ResponseListBean<EducationTeacher> list = new ResponseListBean<EducationTeacher>();
		List<EducationTeacher> teacherList = null;
		try {
			teacherList = iEducationTeacherDao.findEducationTeacherByMobileOrName(content);
			list.setList(teacherList);
			list.setStatus(ResponseStatus.SUCCESS.toString());
		} catch (Exception e) {
			list.setStatus(ResponseStatus.FAILED.toString());
		}
		return list;
	}

	// ================================================================

	@Override
	public PageBean getEducationTeacher(EducationTeacher educationTeacher, Integer currentPage, Integer pageSize) {

		int recordCount = iEducationTeacherDao.getTeacherCount(educationTeacher);
		List<EducationTeacher> list = iEducationTeacherDao.getTeacher(educationTeacher, currentPage, pageSize);
		for (EducationTeacher teacher : list) {
			teacher.setGroup(null);
			teacher.setGroups(null);
			teacher.setHomeWorkList(null);
		}
		PageBean bean = new PageBean(currentPage, pageSize, recordCount, list);

		return bean;
	}

	@Override
	@Transactional
	public Boolean deleteTeacherById(Integer teacherId) {
		return iEducationTeacherDao.delete(teacherId, EducationTeacher.class);
	}

	@Override
	public EducationTeacherResponse findTeacherById(Integer teacherId) {

		EducationTeacher educationTeacher = iEducationTeacherDao.get(EducationTeacher.class, teacherId);
		EducationTeacherResponse educationTeacherResponse = new EducationTeacherResponse();
		if (educationTeacher != null) {
			educationTeacher.setGroup(null);
			educationTeacher.setGroups(null);
			educationTeacher.setPassword(null);
			educationTeacher.setHomeWorkList(null);
			BeanUtils.copyProperties(educationTeacher, educationTeacherResponse);
		}
		return educationTeacherResponse;
	}

	@Override
	@Transactional
	public Boolean updateTeacher(EducationTeacher newTeacher) {

		String[] ignoreProperties = GetNullProperties.getNullProperties(newTeacher);
		System.out.println(ignoreProperties);
		EducationTeacher oldTeacher = iEducationTeacherDao.get(EducationTeacher.class, newTeacher.getId());
		BeanUtils.copyProperties(newTeacher, oldTeacher, ignoreProperties);
		if (oldTeacher.getSchool() != null && oldTeacher.getSchool().getId() == null) {
			oldTeacher.setSchool(null);
		}
		if (oldTeacher.getSubject() != null && oldTeacher.getSubject().getId() == null) {
			oldTeacher.setSubject(null);
		}
		/* teacher.setPassword(PasswordUtils.encodPassword(teacher.getPassword())); */

		return iEducationTeacherDao.merge(oldTeacher);
	}

	@Override
	@Transactional
	public Boolean addTeacher(EducationTeacher teacher) {
		if (teacher.getSchool() != null && teacher.getSchool().getId() == null) {
			teacher.setSchool(null);
		}
		if (teacher.getSubject() != null && teacher.getSubject().getId() == null) {
			teacher.setSubject(null);
		}
		teacher.setPassword(PasswordUtils.encodPassword(teacher.getPassword()));

		return iEducationTeacherDao.save(teacher);
	}

	@Override
	public ResponseListBean<EducationTeacher> findTeacherByCondition(EducationTeacher teacher) {

		List<EducationTeacher> list = iEducationTeacherDao.findTeacherByCondition(teacher);
		ResponseListBean<EducationTeacher> responseList = new ResponseListBean<EducationTeacher>();
		if (list != null) {
			responseList.setList(list);
		}
		return responseList;
	}

	@Value("${com.productE.images}")
	private String path;

	@Transactional
	@Override
	public EducationTeacherResponse modifyTeacherInfo(EducationTeacher bean, MultipartFile file, String url) {
		EducationTeacherResponse response = new EducationTeacherResponse();
		EducationTeacher teacher = new EducationTeacher();
		teacher = iEducationTeacherDao.get(EducationTeacher.class, bean.getId());
		System.out.println(bean.toString());
		System.out.println(teacher.toString());
		//s 判断是否上传了头像
		if (file != null) {
			//s 获取数据库中原头像存储的地址 并删除原头像
			if (teacher.getHeadImage() != null && !teacher.getHeadImage().equals("")) {
				String oldurl = teacher.getHeadImage().substring(teacher.getHeadImage().lastIndexOf(File.separator)+1);
				File deleteFile = new File(path + File.separator + oldurl);
				if (deleteFile.exists() && deleteFile.isFile()) {
					deleteFile.delete();
				}
			}
			//s 将新头像存储在磁盘内
			File saveFile = new File(path + File.separator + file.getOriginalFilename());
			try {
				file.transferTo(saveFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			BeanCopyNotNull.copyNotNullAndPrimitiveFiled(bean, teacher);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		//s	如果头像不为空 则设置头像地址
		if(file != null) {
			teacher.setHeadImage(url + File.separator + file.getOriginalFilename());
		}
		//s  判断用户是否进行了修改学校的操作
		if (bean.getSchool() != null) {
			if (bean.getSchool().getId() != null) {
				EducationSchool school = iEducationSchoolDao.get(EducationSchool.class, bean.getSchool().getId());
				if (school != null) {
					teacher.setSchool(school);
				} else {
					response.setStatus(ResponseStatus.FAILED.toString());
					response.setMessage("该学校不存在");
					return response;
				}
			}
		}
		boolean status = iEducationTeacherDao.update(teacher);
		if (status == false) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("修改信息失败");
		} else {
			response.setStatus(ResponseStatus.SUCCESS.toString());
			response.setMessage("修改信息成功");
		}
		return response;
	}

	@Transactional
	@Override
	public ResponseBean quitGroup(String groupId, String teacherId) {
		ResponseBean response = new ResponseBean();
		EducationGroup group = iEducationGroupDao.get(EducationGroup.class, Long.parseLong(groupId));
		if (group != null) {
			EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, Integer.parseInt(teacherId));
			if (teacher != null) {
				if (group.getTeachers().contains(teacher)) {
					group.getTeachers().remove(teacher);
					boolean status = iEducationGroupDao.save(group);
					if (status == false) {
						response.setStatus(ResponseStatus.FAILED.toString());
						response.setMessage("退出群组失败，请重新尝试");
					} else {
						response.setStatus(ResponseStatus.SUCCESS.toString());
						response.setMessage("退出群组成功");
					}
				} else {
					response.setStatus(ResponseStatus.FAILED.toString());
					response.setMessage("群组中不存在此老师");
				}
			} else {
				response.setStatus(ResponseStatus.FAILED.toString());
				response.setMessage("教师不存在");
			}
		} else {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("群组不存在");
		}
		return response;
	}
	
	/**
	 * @Description 修改密码
	 * @author Leon
	 * @date   Nov 27, 2018
	 * @param  
	 * @return ResponseBean
	 */
	@Transactional
	@Override
	public ResponseBean changePassword(String id, String oldPassword, String newPassword) {
		ResponseBean response = new ResponseBean();
		oldPassword = PasswordUtils.encodPassword(oldPassword);
		EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, Integer.parseInt(id));
		if( teacher !=null ) {
			if(oldPassword.equals(teacher.getPassword())) {
				teacher.setPassword(PasswordUtils.encodPassword(newPassword));
				boolean status = iEducationTeacherDao.save(teacher);
				if(status == false) {
					response.setStatus(ResponseStatus.FAILED.toString());
					response.setErrorCode("2");
					response.setMessage("密码修改失败，请重新尝试");
				}else {
					response.setStatus(ResponseStatus.SUCCESS.toString());
				}
			}else {
				response.setStatus(ResponseStatus.FAILED.toString());
				response.setMessage("原密码不正确");
				response.setErrorCode("1");
			}
		}else {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("该教师不存在");
			response.setErrorCode("0");
		}
		return response;
	}

}
